package main

import (
	"flag"
	"log"
	"os/exec"
)

var (
	Mode       = flag.String("mode", "tun", "tun or tap")
	DevName    = flag.String("name", "tun0", "device's name")
	IPAddr     = flag.String("ip", "", "ip address")
	DelDevName = flag.String("del", "", "delete device")
)

func init() {
	flag.Parse()
}

func main() {
	if *DelDevName != "" {
		out, err := exec.Command("ip", "link", "del", *DelDevName).Output()
		if err != nil {
			log.Fatal(string(err.(*exec.ExitError).Stderr))
		}
		log.Println("del device. " + string(out))
		return
	}

	// 添加设备
	out, err := exec.Command("ip", "tuntap", "add", "dev", *DevName, "mode", *Mode).Output()
	if err != nil {
		log.Fatal(string(err.(*exec.ExitError).Stderr))
	}
	log.Println("add device. " + string(out))

	// 给网卡添加ip地址
	if *IPAddr != "" {
		out, err = exec.Command("ip", "addr", "add", *IPAddr, "dev", *DevName).Output()
		if err != nil {
			log.Fatal(string(err.(*exec.ExitError).Stderr))
		}
		log.Println("add ipaddr. " + string(out))
	}

	// 启动设备
	out, err = exec.Command("ip", "link", "set", *DevName, "up").Output()
	if err != nil {
		log.Fatal(string(err.(*exec.ExitError).Stderr))
	}
	log.Println("up device. " + string(out))
}
